<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Articles;
use DB,Validator,View,Gate,Auth,Response;
use Stevenyangecho\UEditor\UEditorServiceProvider as UEditor;

class ArticleController extends Controller
{

    //insert article
    protected function insert(Request $request)
    {
    	$validator = Validator::make($request->all(), [
            'title' => 'required|min:6|max:40',
            'tag' => 'max:24',
            'content' => 'required|min:10'
        ]);

    	if($validator->fails()){
    		return redirect('article/create')->withErrors($validator)->withInput();
    	}

		$rs = Articles::create($request->all() + ['user_id' => Auth::user()->id]);
        #Todo 返回之前页面
        return redirect(route('index'));
    }

    //show insert form
    public function create()
    {
    	return View::make('article.create');
    }

    public function edit(Request $request)
    {
        $article = Articles::where('id', $request->input('id'))->firstOrFail();
        // var_dump(Gate::denies('update', $article));die;
        return View::make('article.edit')->with(['article' => $article, 'id' => $request->input('id')]);
    }

    public function update(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'title' => 'required|min:15',
            'tag' => 'max:80',
            'content' => 'required|min:12'
        ]);

        if($validator->fails()){
            return redirect()->back()->withErrors($validator)->withInput();
        }

        $rs = Articles::where('id', $request->input('id'))->first()->update($request->only(['title', 'tag', 'content']));
        #Todo 返回之前页面

        return redirect('index');
    }

    public function comments(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'content' => 'required|min:5'
        ]);

        if($validator->fails()){
            #Todo 展示错误
            return redirect()->back()->withErrors($validator)->withInput();
        }

        $rs = DB::table('comments')->insert(
            ['a_id'=>$request->input('aid'),
             'content'=>$request->input('content'),
             'p_id'=>(!is_null($request->input('pid'))?$request->input('pid'):0),
             'u_id'=>Auth::user()->id]
             );
        #Todo 返回之前页面
        return redirect()->back();
    }
}
